package com.xquant.marketdata.marketdata.service;

import com.xquant.marketdata.marketdata.config.SSLClient;
import com.xquant.marketdata.marketdata.mapper.TcmdtforwardSeriesMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;

/**
 * @author xpp
 * @version 1.0
 * @date 2020/10/12 10:33
 */
@Service
public class TcmdtforwardSeriesService {

    private static Logger logger = LoggerFactory.getLogger(TcmdtforwardSeriesService.class);

    @Autowired
    private TcmdtforwardSeriesMapper tcmdtforwardSeriesMapper;

    public List<String> getData(String start, String end) throws IOException {
        if (StringUtils.isBlank(start)) {
            //默认前一天
            start = LocalDate.now().plusDays(-1).toString();
        }
        if (StringUtils.isBlank(end)) {
            //默认今天
            end = LocalDate.now().toString();
        }
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        HttpGet httpGet = null;
        List<String> results = new ArrayList();
        try {
            httpClient = new SSLClient();
            httpGet = new HttpGet("https://www.sge.com.cn/qxcx/count?forwardType=all&startDateCount=" + start + "&endDateCount=" + end);
            HttpResponse pagesize = httpClient.execute(httpGet);
            //得到分页数
            HttpEntity res = pagesize.getEntity();
            int pages = 1;
            if (res != null) {
                double v = Double.parseDouble(EntityUtils.toString(res));
                pages = (int) Math.ceil(v / 10.0);
            }
            for (int i = 0; i < pages; i++) {
                //只有黄金
                //httpPost = new HttpPost("https://www.sge.com.cn/sjzx/yqjgqxdata?forwardType=all"+"&forwardType=gold&start="+start+"&end="+end+"&pagesize="+i);
                //黄金、白银
                httpPost = new HttpPost("https://www.sge.com.cn/sjzx/yqjgqxdata?forwardType=all" + "&start=" + start + "&end=" + end + "&pagesize=" + i);
           /*
            httpPost.addHeader("Content-Type", "application/json");
            StringEntity se = new StringEntity(jsonstr);
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            httpPost.setEntity(se);*/
                HttpResponse response = httpClient.execute(httpPost);
                if (response != null) {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        results.add(EntityUtils.toString(resEntity));
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return results;
    }


    private List<HashMap<String, String>> analysisHTML(String html) {
//        System.out.println(html);
        //6.Jsoup解析html
        Document document = Jsoup.parse("<table>" + html + "</table>");
        //像js一样，通过标签获取title
        Elements tList = document.getElementsByTag("tr");
        //像js一样，通过class 获取列表下的所有博客
        List<String> title = new ArrayList();
        List<String> content = new ArrayList();
        List<HashMap<String, String>> maps = new ArrayList<>();
        for (Element e : tList.first().getElementsByTag("th").not("th[class='hide']")) {
            title.add(e.text().replace(" ", ""));
        }
        for (int i = 1; i < tList.size(); i++) {
            HashMap<String, String> temp = new HashMap<>();
            Elements td = tList.get(i).getElementsByTag("td").not("td[class='hide']");

            for (int j = 0; j < td.size(); j++) {
                temp.put(title.get(j), td.get(j).text());
                content.add(td.get(j).text().trim());
            }
            maps.add(temp);
        }
        //System.out.println(maps.toString());
        return maps;
    }

    //一个map渲染出8条记录,第一步
    private List<Map<String, String>> generateMaps(HashMap<String, String> map) {
        Set<String> strings = map.keySet();
        String date = map.get("日期");
        String variety = map.get("品种");
        // variety = variety.substring(1, variety.length());
        //O/N	1W	2W	1M	3M	6M	9M	1Y
        strings.remove("日期");
        strings.remove("品种");
        /*strings.remove("3W");
        strings.remove("4M");
        strings.remove("5M");
        strings.remove("2M");*/
        ArrayList<Map<String, String>> maps = new ArrayList<>();
        for (String t : strings) {
            Map<String, String> generateMap = generateMap(map, t, date, variety);
            maps.add(generateMap);
        }

        return maps;
    }

    //一个map渲染出8条记录,第二步
    private Map<String, String> generateMap(HashMap<String, String> dataMap, String key, String date, String variety) {
        String value = dataMap.get(key);//从金交所上抓的数据需要除100后导入库里，否则剥离不出结果
        double v = Double.parseDouble(value);
        v = v / 100.0;
        value = String.valueOf(v);
        switch (variety) {
            case "AUX.CNY":
                variety = "Au99.95";
                break;
            case "AUY.CNY":
                variety = "Au99.99";
                break;
            default:
                break;
        }
        HashMap<String, String> map = new HashMap<>();//Au99.99_ATM_3M
        map.put("iCode", variety + "_" + key);
        map.put("aType", "FWD_CMDT");
        map.put("mType", "SGEX");
        map.put("source", "Manual");
        map.put("begDate", date);
        map.put("endDate", java.sql.Date.valueOf(date).toLocalDate().plusDays(1).toString());
        map.put("dpBid", value);
        map.put("dpAsk", value);
        map.put("dpMid", value);
        map.put("pipeId", "-1");
        map.put("impDate", LocalDate.now().toString());
        map.put("impTime", LocalTime.now().toString());
        map.put("sourceTime", "");

        return map;
    }


    public String importQuote(String start, String end) throws IOException {
        List<String> dataList = this.getData(start, end);
        int importCount = 0;
        for (String data : dataList) {
            List<Map<String, String>> datas = new ArrayList<>();
            List<HashMap<String, String>> maps = analysisHTML(data);
            for (HashMap<String, String> map : maps) {
                List<Map<String, String>> maps1 = generateMaps(map);
                datas.addAll(maps1);
            }
            for (Map<String, String> map : datas) {
                HashMap hashMap = tcmdtforwardSeriesMapper.selectByPrimaryKey((HashMap) map);
                if (null == hashMap) {
                    tcmdtforwardSeriesMapper.insert((HashMap) map);
                    importCount++;
                } else {
                    logger.info("数据库已有该条数据：" + hashMap.toString());
                }
            }
        }

        return "金交所远期价格曲线数据导入成功，共" + importCount + "条数据";
    }
}
